package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.common.anno.GuiguCache;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.model.album.*;
import com.atguigu.tingshu.vo.album.AlbumCategoryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

	@Autowired
	private BaseCategory1Mapper baseCategory1Mapper;

	@Autowired
	private BaseCategory2Mapper baseCategory2Mapper;

	@Autowired
	private BaseCategory3Mapper baseCategory3Mapper;

	@Autowired
	BaseCategoryViewMapper baseCategoryViewMapper;

	@Autowired
	BaseAttributeMapper baseAttributeMapper;

	@Override
	public List<AlbumCategoryVo> getBaseCategoryList() {
		return baseCategoryViewMapper.getBaseCategoryList();
	}

	@Override
	public List<BaseAttribute> findAttributeByCategoryId(Long category1Id) {
		return baseAttributeMapper.findAttributeByCategoryId(category1Id);
	}
	@GuiguCache(cacheKey = RedisConstant.CATEGORY_INFO_PREFIX,enableLock = true,lockName = RedisConstant.CATEGORY_LOCK_PREFIX)
	@Override
	public BaseCategoryView findCategoryByC3Id(Long c3Id) {
		return baseCategoryViewMapper.selectById(c3Id);
	}

	@Override
	public AlbumCategoryVo findCategoryByC1Id(Long category1Id) {
		return baseCategoryViewMapper.findCategoryByC1Id(category1Id);
	}

	@Override
	public List<BaseCategory3> findTopBaseCategory3ByCategory1Id(Long category1Id) {
		//	先根据一级分类Id 找到二级分类集合
		LambdaQueryWrapper<BaseCategory2> baseCategory2LambdaQueryWrapper = new LambdaQueryWrapper<>();
		baseCategory2LambdaQueryWrapper.eq(BaseCategory2::getCategory1Id,category1Id);
		baseCategory2LambdaQueryWrapper.select(BaseCategory2::getId);
		List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(baseCategory2LambdaQueryWrapper);
		List<Long> category2IdList = baseCategory2List.stream().map(BaseCategory2::getId).toList();
		//	查询置顶消息
		LambdaQueryWrapper<BaseCategory3> wrapper = new LambdaQueryWrapper<>();
		// last("limit 7") 查询前7条
		wrapper.in(BaseCategory3::getCategory2Id,category2IdList).eq(BaseCategory3::getIsTop,1).last("limit 7");
		// 查询数据返回结果
		return baseCategory3Mapper.selectList(wrapper);
	}
}
